package cn.tsyz.local.shared.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*", filterName = "myFilter")
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        String requestURI = httpRequest.getRequestURI();
        String method = httpRequest.getMethod();
        String clientIP = getClientIP(httpRequest);
        String userAgent = httpRequest.getHeader("User-Agent");

        // 请求前处理 - 记录请求信息
        log.info("=== 请求开始 ===");
        log.info("客户端IP: {}", clientIP);
        log.info("请求方法: {}", method);
        log.info("请求URI: {}", requestURI);
        if (userAgent != null) {
            log.info("User-Agent: {}", userAgent);
        }

        // 继续执行过滤器链
        chain.doFilter(request, response);

        // 响应后处理 - 记录响应信息
        long duration = System.currentTimeMillis() - startTime;
        log.info("=== 请求结束 ===");
        log.info("响应状态: {}", httpResponse.getStatus());
        log.info("处理耗时: {}ms", duration);
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
